package com.hwl.server.handler.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hwl.server.entity.Employee;
import com.hwl.server.entity.MailLog;
import com.hwl.server.service.EmployeeService;
import com.hwl.server.service.MailLogService;
import com.hwl.server.utils.MailConstants;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 邮件发送定时任务
 */
@Component
public class MailTask {
    @Resource
    private MailLogService mailLogService;
    @Resource
    private EmployeeService employeeService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 邮件发送定时任务
     * 10秒检查一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask() {
        //状态为0即消息在投递中，且重试时间小于当前时间的才需要重新发送
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>()
                .eq("status", MailConstants.DELIVERING)
                .lt("tryTime", LocalDateTime.now()));

        list.forEach(mailLog -> {
            String msgId = mailLog.getMsgId();
            //重试次数超过最大次数，更新状态为投递失败，不再重试
            if (mailLog.getCount() >= MailConstants.MAX_TRY_COUNT) {
                mailLogService.update(new UpdateWrapper<MailLog>()
                        .set("status", MailConstants.FAILURE)
                        .set("updateTime", LocalDateTime.now())
                        .eq("msgId", msgId));
            }
            //更新重试次数，更新时间，重试时间
            mailLogService.update(new UpdateWrapper<MailLog>()
                    .set("count", mailLog.getCount() + 1)
                    .set("updateTime", LocalDateTime.now())
                    .set("tryTime", LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT))
                    .eq("msgId", msgId));

            Employee employee = employeeService.getEmployee(mailLog.getEid()).get(0);
            //发送信息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME, MailConstants.MAIL_ROUTING_KEY_NAME,
                    employee, new CorrelationData(msgId));
        });
    }
}
